<template>
  <div class="max-w-[1600px] mx-auto">
    <div class="flex flex-col lg:flex-row gap-6">
      <!-- 左侧输入区域 -->
      <div :class="`w-full ${isFullscreen ? 'hidden' : 'lg:w-2/5'}`">
        <div class="bg-white rounded-xl shadow-sm p-6">
          <h1 class="text-2xl font-bold mb-4">输入你的问题</h1>
          
          <div class="flex space-x-2 mb-6">
            <button
              @click="setInputMethod('text')"
              :class="`flex-1 py-2 px-4 rounded-md ${
                inputMethod === 'text'
                  ? 'bg-blue-100 text-blue-700 font-medium'
                  : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
              } transition-colors`"
            >
              文本输入
            </button>
            <button
              @click="setInputMethod('image')"
              :class="`flex-1 py-2 px-4 rounded-md ${
                inputMethod === 'image'
                  ? 'bg-blue-100 text-blue-700 font-medium'
                  : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
              } transition-colors`"
            >
              图片上传
            </button>
          </div>
          
          <transition
            name="fade"
            mode="out-in"
          >
            <div v-if="inputMethod === 'text'" key="text-input">
              <label class="block text-sm font-medium text-gray-700 mb-2">
                输入数学问题
              </label>
              <textarea
                v-model="textInput"
                @input="setError(null)"
                placeholder="例如：求解 x^2 - 5x + 6 = 0"
                class="w-full h-32 px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-none"
              />
              
              <div v-if="textInput" class="mt-4 p-3 bg-gray-50 rounded-md">
                <p class="text-sm text-gray-600 mb-2">预览：</p>
                <BlockMath :math="textInput" />
              </div>
            </div>
            <div v-else key="image-input">
              <div v-if="!uploadedImage" 
                v-bind="getRootProps()"
                :class="`border-2 border-dashed rounded-lg p-8 text-center cursor-pointer transition-colors ${
                  isDragActive ? 'border-blue-400 bg-blue-50' : 'border-gray-300 hover:border-blue-400'
                }`"
              >
                <input v-bind="getInputProps()" />
                <Upload class="mx-auto h-12 w-12 text-gray-400 mb-2" />
                <p class="text-gray-600">
                  拖放图片到此处，或点击选择图片
                </p>
                <p class="text-sm text-gray-500 mt-1">
                  支持的格式：JPG、PNG（小于5MB）
                </p>
              </div>
              <div v-else class="relative">
                <img
                  :src="uploadedImage"
                  alt="上传的数学问题"
                  class="w-full rounded-md"
                />
                <button
                  @click="setUploadedImage(null)"
                  class="absolute top-2 right-2 p-1 bg-white rounded-full shadow-md hover:bg-gray-100"
                  aria-label="删除图片"
                >
                  <X class="w-4 h-4" />
                </button>
              </div>
            </div>
          </transition>
          
          <transition
            enter-active-class="transition-all duration-200 ease-out"
            leave-active-class="transition-all duration-150 ease-in"
            enter-from-class="opacity-0 -translate-y-2"
            enter-to-class="opacity-100 translate-y-0"
            leave-from-class="opacity-100 translate-y-0"
            leave-to-class="opacity-0 -translate-y-2"
          >
            <div v-if="error" class="mt-4 p-3 bg-red-50 border border-red-100 rounded-md">
              <div class="flex items-start">
                <AlertCircle class="h-5 w-5 text-red-500 mt-0.5 mr-2" />
                <div>
                  <p class="text-red-700 text-sm">{{ error }}</p>
                  <button
                    @click="setError(null)"
                    class="mt-2 text-xs text-red-600 hover:text-red-800"
                  >
                    重试
                  </button>
                </div>
              </div>
            </div>
          </transition>
          
          <div class="mt-6 flex space-x-3">
            <button
              @click="verifyAnswer"
              :disabled="isVerifying || (!textInput && !uploadedImage)"
              :class="`px-4 py-2 rounded-md flex-1 font-medium ${
                isVerifying || (!textInput && !uploadedImage)
                  ? 'bg-gray-200 text-gray-500 cursor-not-allowed'
                  : 'bg-blue-600 text-white hover:bg-blue-700'
              } transition-colors`"
            >
              {{ isVerifying ? '分析中...' : '解答问题' }}
            </button>
            <button
              @click="resetProblem"
              class="px-4 py-2 rounded-md border border-gray-300 text-gray-700 hover:bg-gray-50 transition-colors"
            >
              清空
            </button>
          </div>

          <transition
            enter-active-class="transition-all duration-200 ease-out"
            leave-active-class="transition-all duration-150 ease-in"
            enter-from-class="opacity-0 translate-y-4"
            enter-to-class="opacity-100 translate-y-0"
            leave-from-class="opacity-100 translate-y-0"
            leave-to-class="opacity-0 translate-y-4"
          >
            <div v-if="feedback" class="mt-6 p-4 bg-blue-50 rounded-lg border border-blue-100">
              <h3 class="font-medium text-blue-800 mb-2">实时反馈：</h3>
              <div class="text-blue-700 whitespace-pre-line">
                {{ feedback }}
              </div>
            </div>
          </transition>
        </div>

        <!-- 解题步骤输入区域 -->
        <div class="bg-white rounded-xl shadow-sm p-6 mt-6">
          <div class="flex items-center mb-4">
            <FileText class="h-5 w-5 text-gray-500 mr-2" />
            <h2 class="text-lg font-semibold text-gray-900">解题步骤</h2>
          </div>
          <p class="text-sm text-gray-600 mb-4">
            在这里记录你的解题思路和步骤，支持 Markdown 格式和数学公式
          </p>
          
          <MDEditor
            v-model="solutionSteps"
            preview="edit"
            hideToolbar="false"
            :textareaProps="{
              placeholder: '请输入你的解题步骤...\n\n例如：\n1. 首先分析题目条件\n2. 建立数学模型\n3. 求解方程\n\n支持数学公式：$x = \\frac{-b \\pm \\sqrt{b^2-4ac}}{2a}$',
              style: { fontSize: '14px', lineHeight: '1.6', minHeight: '150px' }
            }"
            height="200px"
          />
          
          <div v-if="solutionSteps" class="mt-4 p-3 bg-gray-50 rounded-md">
            <p class="text-sm text-gray-600 mb-2">预览：</p>
            <div class="prose prose-sm max-w-none">
              <MDEditor.Markdown :source="solutionSteps" />
            </div>
          </div>
        </div>

        <div class="mt-6">
          <OperationHistory 
            :operations="operations"
            @undo="handleUndo"
          />
        </div>
      </div>
      
      <!-- 右侧GeoGebra区域 -->
      <div :class="`w-full ${isFullscreen ? 'h-screen' : 'lg:w-3/5 h-[calc(100vh-8rem)]'}`">
        <div :class="`bg-white rounded-xl shadow-sm ${isFullscreen ? '' : 'p-6'} h-full flex flex-col`">
          <div class="flex-1 relative">
            <GeoGebraEmbed 
              @ready="setGgbApp"
              :isFullscreen="isFullscreen"
              @toggleFullscreen="setIsFullscreen(!isFullscreen)"
              @action="handleGeoGebraAction"
              :mode="geogebraMode"
              @modeChange="setGeogebraMode"
            />
          </div>
        </div>
      </div>
    </div>

    <!-- 问题解答区 -->
    <div class="mt-6">
      <div class="bg-white rounded-xl shadow-sm p-6">
        <h2 class="text-xl font-bold mb-4">问题解答区</h2>
        <SolutionVerifier
          v-if="problemId"
          :operations="operations"
          :problemType="inputMethod === 'text' ? textInput : 'geometric'"
          @feedback="setFeedback"
          @verificationResult="setVerificationResult"
        />
        
        <div v-if="verificationResult" class="mt-4">
          <div v-if="verificationResult.score !== undefined" class="mt-4">
            <h4 class="font-medium text-gray-700 mb-2">得分：</h4>
            <div class="flex items-center">
              <div class="flex-1 h-2 bg-gray-200 rounded-full">
                <div 
                  class="h-full bg-blue-500 rounded-full"
                  :style="{ width: `${verificationResult.score * 100}%` }"
                />
              </div>
              <span class="ml-3 text-gray-600">
                {{ Math.round(verificationResult.score * 100) }}分
              </span>
            </div>
          </div>
          <div v-if="verificationResult?.demonstration?.steps?.length > 0" class="mt-6 p-4 bg-gray-50 border border-gray-200 rounded-md">
            <h3 class="text-base font-semibold mb-2 text-gray-800">AI 解答步骤</h3>
            <ol class="list-decimal list-inside space-y-1 text-sm text-gray-700">
              <li v-for="(step, index) in verificationResult.demonstration.steps" :key="index">
                <strong>{{ step.command }}</strong> - {{ step.description }}
              </li>
            </ol>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue';
import { useDropzone } from 'vue3-dropzone';
import GeoGebraEmbed from '../components/interactive/GeoGebraEmbed.vue';
import OperationHistory from '../components/interactive/OperationHistory.vue';
import SolutionVerifier from '../components/interactive/SolutionVerifier.vue';
import { 
  Upload, 
  X, 
  AlertCircle, 
  ChevronRight, 
  FileText 
} from 'lucide-vue-next';
// import { problemService } from '../services/apiService';
import axios from 'axios';

const ggbApp = ref(null);
const isFullscreen = ref(false);
const inputMethod = ref('text');
const textInput = ref('');
const solutionSteps = ref('');
const uploadedImage = ref(null);
const isVerifying = ref(false);
const error = ref(null);
const feedback = ref(null);
const geogebraMode = ref('2D');
const operations = ref([]);
const problemId = ref(null);
const verificationResult = ref(null);

const { getRootProps, getInputProps, isDragActive } = useDropzone({
  accept: ['image/*'],
  maxSize: 5 * 1024 * 1024, // 5MB
  onDrop: (acceptedFiles) => {
    const file = acceptedFiles[0];
    if (file) {
      const previewUrl = URL.createObjectURL(file);
      uploadedImage.value = previewUrl;
      error.value = null;
    }
  }
});

const handleGeoGebraAction = async (action) => {
  operations.value = [...operations.value, action];
  
  if (problemId.value) {
    try {
      await digitalTwinService.recordAction(action, problemId.value);
    } catch (err) {
      console.error('Failed to record action:', err);
    }
  }
};

const handleUndo = () => {
  if (operations.value.length > 0) {
    operations.value = operations.value.slice(0, -1);
  }
};

const verifyAnswer = async () => {
  isVerifying.value = true;
  error.value = null;

  try {
    const submissionPayload = {
      studentId: "temp_student",
      questionId: "Q101",
      diagramXML: ggbApp.value?.getXML?.() || "",
      operations: operations.value.map(op => ({
        action: op.action,
        object: op.object,
        type: op.type,
        time: op.time
      })),
      answers: {
        textAnswer: inputMethod.value === "text" ? textInput.value : "",
        markdownAnswer: solutionSteps.value || "",
        imageBase64: uploadedImage.value || ""
      }
    };

    if (!uploadedImage.value) delete submissionPayload.answers.imageBase64;
  
    const response = await axios.post("/submit", submissionPayload);

    const result = response.data;
    feedback.value = result.feedback || "收到 AI 反馈";
    verificationResult.value = result.verification || null;

  } catch (err) {
    console.error("提交失败:", err);
    error.value = "提交失败，请稍后重试。";
  } finally {
    isVerifying.value = false;
  }
};

const resetProblem = () => {
  textInput.value = '';
  solutionSteps.value = '';
  uploadedImage.value = null;
  error.value = null;
  feedback.value = null;
  problemId.value = null;
  operations.value = [];
  verificationResult.value = null;
};

const setGgbApp = (app) => {
  ggbApp.value = app;
};

const setInputMethod = (method) => {
  inputMethod.value = method;
};

const setError = (err) => {
  error.value = err;
};

const setFeedback = (fb) => {
  feedback.value = fb;
};

const setIsFullscreen = (value) => {
  isFullscreen.value = value;
};

const setGeogebraMode = (mode) => {
  geogebraMode.value = mode;
};

const setVerificationResult = (result) => {
  verificationResult.value = result;
};
</script>

<style>
/* 自定义过渡效果 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.2s, transform 0.2s;
}
.fade-enter-from,
.fade-leave-to {
  opacity: 0;
  transform: translateY(10px);
}
</style>
